$(function () {
  $(".tab4").click(function () {
    $('#install_reminder').html('验证中,请稍候...');
    $('#install_button').attr('disabled',true);
    preInstall();
  });
  
  $("#install_button").click(function () {
      $('#install_button').attr('disabled',true);//click安装按钮后disabled
      install();
  });
  
  $('#waiting').dialog({
      autoOpen: false,
      resizable: false,
      modal: false,
      width: 500,
      height:300,
      buttons: {
        "关闭": function() {
           $( this ).dialog( "close" );
        }
      }
  });
  
});

function preInstall() {
  //校验被推广的宝贝是否超过最大数量
  var toBePromotedNum = getToBePromotedNum();
  var validatePass = validateToBePromoteMaxNum(toBePromotedNum);
  if(!validatePass){
    return;
  }
  
  //校验被推广的宝贝是否为0
  var intelligence_nums = $("#num_1").val();
  var is_intell_close = $('input[name=intell_switch]:checked').val();
  if(is_intell_close == 'intell_off'){
    intelligence_nums = 0;
  }
  validatePass = validateToBePromoteMinNum(toBePromotedNum,intelligence_nums);
  if(!validatePass){
    return;
  }
  
  var installSetting = $('input[name=promot]:checked').val();
  var sellerCats = '';
  $("input[name=seller_cats_promote]:checked").each(function(){
      sellerCats+=$(this).val()+",";
  });
  var itemCats = '';
  $("input[name=item_cats_promote]:checked").each(function(){
      itemCats+=$(this).val()+",";
  });
  var toPromoteNum= getToPromoteNum();
  
  //校验安装的宝贝是否为0
  validatePass = validateToPromoteNum(installSetting,sellerCats,itemCats,toPromoteNum);
  if(!validatePass){
    return;
  }
  
  //校验是否在第2步中选择样式
  validatePass= validateStyleInfo();
  if(!validatePass){
    return;
  }
  
  //校验是否在第3步中选择安装位置
  validatePass = validateInstallPlace();
  if(!validatePass){
    return;
  }

  var params = {
      "ipro.install_setting":installSetting,
      "ipro.seller_cats":sellerCats,
      "ipro.item_cats":itemCats,
      "ipro.to_promote_num":toPromoteNum,
      "ipro.install_place":getInstallPlace()
  };
 $.post("preInstall.action", params, processPreResponse, "json");
}

//校验被推广的宝贝是否超过最大数量
function validateToBePromoteMaxNum(toBePromotedNum){
  var version_no = $("#version_no").val();
  var maxPromoteNum = 20;
  if(version_no==3){
     maxPromoteNum = 80;
  }else if(version_no==2){
     maxPromoteNum = 30;
  }else{
     maxPromoteNum = 10;
  }
  if(toBePromotedNum > maxPromoteNum){
    var text ="第1步中选择了太多宝贝，您的版本最多只支持";
    text+= maxPromoteNum+"个，请<a target='_blank' style='text-decoration:underline;color:blue' href='http://www.ambitor.net/notice_detail.action?article.article_id=2'>升级为更高版本</a>";
    $('#install_reminder').html(text);
    $('#install_button').attr('disabled',true);
    return false;
  }
  return true;
}

//校验被推广的宝贝是否为0
function validateToBePromoteMinNum(toBePromotedNum,intelligence_nums){
  if(parseInt(toBePromotedNum)+parseInt(intelligence_nums) ===0){
    var text ="请在第1步中选择您要推广的宝贝。";
    $('#install_reminder').html(text);
    $('#install_button').attr('disabled',true);
    return false;
  }
  return true;
}

//校验安装的宝贝是否为0
function validateToPromoteNum(installSetting,sellerCats,itemCats,toPromoteNum){
  var isPass = true;
  var text = '';
  if(installSetting === 'custom'){
    if(toPromoteNum===0){
      text ="您想把推广模块安装到哪些宝贝上？请在第3步中选择。";
      isPass =false;
    }
  }else if(installSetting ==='someCategory'){
    if(sellerCats===''){
      text ="您想把推广模块安装到哪些类别的宝贝上？请在第3步中选择。";
      isPass =false;
    }
  }else if(installSetting ==='itemCategory'){
    if(itemCats===''){
      text ="您想把推广模块安装到哪些类别的宝贝上？请在第3步中选择。";
      isPass =false;
    }
  }
  if(!isPass){
    $('#install_reminder').html(text);
    $('#install_button').attr('disabled',true);
  }
  return isPass;
}

//校验是否在第2步中选择样式
function validateStyleInfo(){
  var isPass = true;
  var text = '';
  var rowid = $("#styleTable").getGridParam("selrow");
  if(rowid === null){
  	text ="请在第2步中选择或新建样式";
    isPass =false;
  }
  if(!isPass){
    $('#install_reminder').html(text);
    $('#install_button').attr('disabled',true);
  }
	return isPass;
}

//校验安装位置是否已经选择
function validateInstallPlace(){
  var isPass = true;
  var text = '';
  if(getInstallPlace()===null||getInstallPlace()===''){
    text ="您想把推广模块安装到哪些位置？请在第3步中选择。";
    isPass =false;
  }
  if(!isPass){
    $('#install_reminder').html(text);
    $('#install_button').attr('disabled',true);
  }
  return isPass;
}

function processPreResponse(data) {
  var code = data.result.code;
  var text = data.result.msg;
  if(Number(code)>0){
    $('#install_reminder').html("校验通过，请点击确认按钮开始安装");
    $('#install_button').attr('disabled',false);//成功的话显示安装按钮
  }else{
    $('#install_button').attr('disabled',true);
    $('#install_reminder').html(text);
  }
}

function install() {
  var bePromotedItemIds = getBePromotedItemIds();
  var toPromoteItemIds = getToPromoteItemIds();
  
  var intelligence_labels = $("#intelligence_label_1").val();
  var intelligence_nums = $("#num_1").val();
  
  var installSetting = $('input[name=promot]:checked').val();
  
  var sellerCats = '';
  if(installSetting =='someCategory'){
    $("input[name=seller_cats_promote]:checked").each(function(){
      sellerCats+=$(this).val();
      sellerCats+= ',';
    });  
    sellerCats = sellerCats.slice(0,sellerCats.length-1);
  }
  
  var itemCats = '';
  if(installSetting =='itemCategory'){
    $("input[name=item_cats_promote]:checked").each(function(){
      itemCats+=$(this).val();
      itemCats+= ',';
    });  
    itemCats = itemCats.slice(0,sellerCats.length-1);
  }

  var rowid = $("#styleTable").getGridParam("selrow");
  var ret = $("#styleTable").jqGrid("getRowData", rowid);
  if(ret.STYLE_ID == null || ret.STYLE_ID == ""){
  	alert("请到第2步中选择或新建样式");
  	return;
  }
  var params = {
    "ipro.is_intell_close":$('input[name=intell_switch]:checked').val(),
    "ipro.intell_labels":intelligence_labels,
    "ipro.intell_nums":intelligence_nums,
    "ipro.intell_frequency":$("#frequency").val(),
    "ipro.promote_radio":installSetting,
    "ipro.install_place":getInstallPlace(),
    "ipro.install_cids":sellerCats,
    "ipro.be_promoted_iids":bePromotedItemIds,
    "ipro.to_promote_iids":toPromoteItemIds,
    "ipro.title":$("#setTableTitle").val(),
  	"ipro.style_id":ret.STYLE_ID,
    "ipro.item_install_cids":itemCats
  };
  
  $("#progress_bar" ).show();
  $("#install_log_ref" ).hide();
  $('#progress_info').html("准备中...");
  $("#progress_bar" ).progressbar({value: 1});
  $("#waiting").dialog('open');
  $.post("install.action", params, null, "json");
  setTimeout('get_process_info()',1000);
}

function get_process_info(){
  $.post("query_progress.action", null, 
    function (data,status){
      var code =Number(data.result.code);
      var msg = data.result.msg;
      if(code==0){
        $("#progress_bar" ).progressbar({value: 100});
        $("#progress_bar" ).hide();
        $('#progress_info').html(msg+"，安装结束");
        $("#install_log_ref").show();
        resetContext();
      }else if(code>0){
        var percent = data.result.percent;
        $("#progress_bar" ).progressbar({value: percent});
        $('#progress_info').html(msg);
        setTimeout('get_process_info()',1000);
      }else{
        $('#progress_info').html("安装过程中出现错误，请联系我们");
      }
    },
    "json");
}

function processInstallResponse(data,status){
  $("#waiting").hide();
  clearInterval(get_poress_info_m);
  var code = data.result.code;
  var text = data.result.msg;
  if(Number(code)<0){//清除前几步的设置
    $('#install_reminder').html(text);
  }else{
    alert("安装结束");
    resetContext();
    location.href=$('#query_install_log_loaction').val();
  }
}


function resetContext(){
   $('#promot_resp').html("");
   $("#sortable_step1_2").html("");
   $('#step3_ipro_module').html("");
   try{
    $("#gridTable").jqGrid("resetSelection");
    $("#promot_gridTable").jqGrid("resetSelection");
   }catch(e){
   }
}

function getBePromotedItemIds(){
  var iids = "";
  $('#sortable_step1_2 div').each(function(){
    iids += $(this).attr('id')+",";
  });
  iids = iids.slice(0,iids.length-1);
  return iids;
}

function getToPromoteItemIds(){
  var iids = "";
  $('#promot_resp div').each(function(){
    var id = $(this).attr('id')+",";
    id = id.slice(4);
    iids += id;
  });
  iids = iids.slice(0,iids.length-1);
  return iids;
}

function getToPromoteNum(){
  var num = 0;
  $('#promot_resp div').each(function(){
    num++;
  });
  return num;
}

function getToBePromotedNum(){
  var num = 0;
  $('#sortable_step1_2 li').each(function(){
    num++;
  });
  return num;
}

function getInstallPlace(){
  var install_places = '';
  $("input[name=install_place_checkbox]:checked").each(function(){
    install_places+=$(this).val()+",";
  });
  install_places = install_places.slice(0,install_places.length-1);
  return install_places;
}

